package com.fecean.sentinel.controller;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class RateLimiterController {

    /**
     * 速率是每秒一个许可
     */
    final RateLimiter rateLimiter = RateLimiter.create(1.0);

    @GetMapping("/snap1")
    public String snap1(){
        // 没有获取许可则等待
        rateLimiter.acquire();
        log.info("snap1");
        return "成功";
    }

    @GetMapping("/snap2")
    public String snap2(){
        // 5秒内能获取许可则返回true
        if(!rateLimiter.tryAcquire(5, TimeUnit.SECONDS)){
            return "失败";
        }
        log.info("snap2");
        return "成功";
    }
}
